<?php

namespace mpend\modules\user\models;

use Yii;
use yii\db\Exception;
use common\models\user\UserSignin;
use common\models\user\UserSigninLog;
use common\helpers\ArrayHelper;
use common\logics\RewardLogic;
use common\helpers\IpHelper;

/**
 * 日历签到模型
 *
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class SigninForm extends \common\base\Model {

    /**
     * @integer 用户UID
     */
    public $user_id;

    /**
     * @integer 用户UID
     */
    public $lat;

    /**
     * @integer 用户UID
     */
    public $lng;

    /**
     * @integer 用户UID
     */
    public $address;

    /**
     * @var User|null 用户信息
     */
    private $_user;

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['user_id'], 'integer'],
            [['lat', 'lng'], 'number'],
            [['address'], 'string', 'max' => 255],
            [['user_id'], 'validateUser'],
        ];
    }

    /**
     * 校验唯一手机号
     */
    public function validateUser($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $userClass = Yii::$app->user->identityClass;
        $user = $userClass::findIdentity($this->$attribute);
        if (!$user) {
            return $this->addError($attribute, '请登录后再进行签到');
        }
        $this->_user = $user;
        $signed = UserSigninLog::find()->andWhere([
            'user_id' => $user->id,
            'date' => date('Y-m-d'),
        ])->exists();
        if ($signed) {
            return $this->addError($attribute, '已签到无需重复签到');
        }
        //计算签到距离
    }

    /**
     * 签到
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError();
        }
        Yii::error($this->attributes);
        $user = $this->_user;
        $model = UserSignin::findOrNew([
            'user_id' => $user->id
        ]);
        $log = UserSigninLog::findOrNew([
            'user_id' => $user->id,
            'date' => date('Y-m-d'),
        ]);
        $log->setAttributes([
            'location' => $this->address,
            'ip' => IpHelper::ip(),
        ]);
//        $log->setGeometryAttribute('geohash', [
//            $this->lng,
//            $this->lat
//        ]);
        if ($this->lat && $this->lng) {
            $log->setGeometryAttribute('gis', [$this->lng, $this->lat]);
        }
        $amount = UserSigninLog::find()->active()->andWhere([
            'user_id' => $user->id
        ])->count();
        $model->amount = $amount + 1;
        $model->serial = $model->serial + 1;
        $model->last_time = time();

        $transaction = Yii::$app->db->beginTransaction();
        try {
            if (!$log->save()) {
                throw new Exception($log->getErrorMsg());
            }
            if (!$model->save()) {
                throw new Exception($model->getErrorMsg());
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            return $this->dumpError($e->getMessage());
        }
        $this->addReward();
        return $log;
    }

    /**
     * 签到奖励
     */
    public function addReward() {
//        RewardLogic::signin();
    }

}
